package com.boot.project.core.handler;

import com.boot.project.core.annotation.ResponseResult;
import com.boot.project.core.model.result.Result;
import com.boot.project.core.util.RequestUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 执行@ResponseResult注解
 */
@RestControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {

    public static final String RESPONSE_RESULT_ANN = "RESPONSE-RESULT-ANN";

    /**
     * 是否执行@ResponseResult注解
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        HttpServletRequest request = RequestUtils.getRequest();
        ResponseResult ann = (ResponseResult) request.getAttribute(RESPONSE_RESULT_ANN);
        return ann != null;
    }

    /**
     * 如何执行@ResponseResult注解
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        Result result;
        if (body == null) {
            result = Result.success();
        } else if (body instanceof Result) {
            result = (Result) body;
        } else {
            result = Result.success(body);
        }
        return result;
    }
}
